﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace WIAssistant
{
    /// <summary>
    /// Contains Extension methods for random classes.
    /// </summary>
    public static class MiscHelpers
    {
        public static void DeserializeStringList(this List<string> list, string fileName)
        {
            var serializer = new XmlSerializer(typeof(List<string>));
            using (var stream = File.OpenRead(fileName))
            {
                var other = (List<string>)(serializer.Deserialize(stream));
                list.Clear();
                list.AddRange(other);
            }
        }

        // Save an object out to the disk
        public static void SerializeObject<T>(this T toSerialize, String filename)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
            TextWriter textWriter = new StreamWriter(filename);

            xmlSerializer.Serialize(textWriter, toSerialize);
            textWriter.Close();
        }

        // Load an object from the disk
        public static T DeserializeObject<T>(String filename) where T : class
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            try
            {
                TextReader textReader = new StreamReader(filename);
                var result = (T)xmlSerializer.Deserialize(textReader);
                textReader.Close();
                return result;
            }
            catch (FileNotFoundException)
            { }

            return null;
        }


    }
}
